<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 新建一个类的静态成员，用来保存数据库实例
     */
    public static $db = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        self::$db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
    }
    
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        $new_message = array(
            'type'=>'onConnect',
            'client_id'=>$client_id,
            'from_client_id'=>$client_id,
            'from_client_name' => '',
            'head_url'=>'',
            'sub_type'=>'' ,
            'error'=>'0',
            'content'=>nl2br(htmlspecialchars('连接成功')),
            'time'=>date('Y-m-d H:i:s'),
        );
        Gateway::sendToCurrentClient(json_encode($new_message));
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
       $message_data = json_decode($message, true);
       if(!$message_data)
       {
           return ;
       }
       // 根据类型执行不同的业务
       switch($message_data['type'])
       {
           //加入群
       case 'join_group':
                // 判断是否有房间号
                if (!isset($message_data['group_id'])) {
                    $new_message = array(
                        'type'=>'join_group',
                        'client_id'=>$client_id,
                        'from_client_id'=>$client_id,
                        'from_client_name' => '',
                        'head_url'=>'',
                        'sub_type'=>'' ,
                        'error'=>'1',
                        'content'=>nl2br(htmlspecialchars('加群失败')),
                        'time'=>date('Y-m-d H:i:s'),
                    );
                    Gateway::sendToCurrentClient(json_encode($new_message));
                }
                if (!isset($message_data['id'])) {
                    throw new \Exception("\$message_data['id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
                Gateway::bindUid($client_id, $message_data['id']);
                // 把房间号昵称放到session中
                $group_id = $message_data['room_id'];
                $client_name = htmlspecialchars($message_data['client_name']);
                $_SESSION['group_id'] = $group_id;
                $_SESSION['level'] = isset($message_data['level']) ? $message_data['level'] : 1;
                $_SESSION['id'] = $message_data['id'];
                $_SESSION['client_name'] = empty($client_name) ? '游客' : $client_name;
                $_SESSION['head_url'] = isset($message_data['head_url']) ? $message_data['head_url'] : 'http://106.52.105.157:81/uploads/head/head.png';
                // 获取房间内所有用户列表
                $clients_list = Gateway::getClientSessionsByGroup($group_id);
                foreach ($clients_list as $tmp_client_id => $item) {
                    $clients_list[$tmp_client_id] = ['client_name' => $item['client_name'], 'head_url' => $item['head_url'], 'id' => $item['id']];
                }
                $clients_list[$client_id] = ['client_name' => $client_name, 'head_url' => $_SESSION['head_url'], 'id' => $_SESSION['id']];
                $new_message = array('type' => $message_data['type'], 'level' => $_SESSION['level'], 'client_id' => $client_id, 'client_name' => htmlspecialchars($client_name), 'time' => date('Y-m-d H:i:s'));
                Gateway::sendToGroup($group_id, json_encode($new_message));
                Gateway::joinGroup($client_id, $group_id);
              return Gateway::sendToCurrentClient(json_encode($new_message));
            //获取client_id
            case 'get_id';
                $new_message = array(
                    'type' => 'get_id',
                    'client_id' => $client_id,
                    'from_client_id' => $client_id,
                    'from_client_name' => isset($_SESSION['client_name']) ? $_SESSION['client_name'] : '游客',
                    'head_url' => isset($_SESSION['head_url']) ? $_SESSION['head_url'] : '',
                    'to_client_id' => 'all',
                    'content' => nl2br(htmlspecialchars($message_data['content'])),
                    'sub_type' => '',
                    'time' => date('Y-m-d H:i:s'),
                );
                Gateway::sendToCurrentClient(json_encode($new_message));
                return '';
            //离开房间
            case 'leave_group':
                if (!isset($message_data['group_id'])) {
                    throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
                Gateway::leaveGroup($client_id, $message_data['group_id']);
                $new_message = array(
                    'type' => 'leave_room',
                    'client_id' => $client_id,
                    'level' => $_SESSION['level'],
                    'from_client_id' => $client_id,
                    'from_client_name' => isset($_SESSION['client_name']) ? $_SESSION['client_name'] : '游客',
                    'head_url' => isset($_SESSION['head_url']) ? $_SESSION['head_url'] : '',
                    'to_client_id' => 'all',
                    'content' => nl2br(htmlspecialchars($message_data['content'])),
                    'sub_type' => '',
                    'time' => date('Y-m-d H:i:s'),
                );
                Gateway::sendToCurrentClient(json_encode($new_message));
                return '';
                //群聊
           case 'group_chat':
            break;
            //一对一聊天
           case 'one_to_one':
               break;
            // 客户端回应服务端的心跳
            case 'pong':
                return;

       }

   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       GateWay::sendToAll("$client_id logout\r\n");
   }
}
